package com.project.controller.goodsController;

import com.github.pagehelper.PageInfo;
import com.project.bean.GoodsBean;
import com.project.bean.GoodsOrderBean;
import com.project.bean.ReviewBean;
import com.project.service.goodsService.IGoodsService;
import com.project.service.reviewService.IReviewService;
import com.project.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IGoodsService service;
    @Autowired
    private IReviewService reviewService;

    @RequestMapping("/findByItem")
    public PageInfo<GoodsBean> findByItem(int pageNO, String goodsName, String type, String address, Integer storeId){
        return service.findByItem(pageNO, goodsName, type, address, storeId);
    }
    @RequestMapping("/findByName")
    public PageInfo<GoodsOrderBean> findByName(int pageNO, String goodsName, String type, String address, String storeName){
        return service.findByName(pageNO, goodsName,type,address,storeName);
    }
    @RequestMapping("/findById")
    public GoodsBean findById(int goodsId){
        GoodsBean goodsBean = service.findById(goodsId);
        List<ReviewBean> list = reviewService.findByGoodsId(goodsId);
        if(list.size() != 0){
            double n = 0;
            for(int i=0; i<list.size(); i++) {
                n += list.get(i).getScore();
            }
            n = n / list.size();
            BigDecimal b = new BigDecimal(n);
            double f = b.setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
            goodsBean.setScore(f);
            goodsBean.setList(list);
        }
        return goodsBean;
    }

    @RequestMapping("/add")
    public String add(GoodsBean goods, Integer sd,@RequestParam("face") MultipartFile mf)throws Exception{
        String fileName = UploadUtil.upload(mf,"static/html/img");
        goods.setImg(fileName);

        service.add(goods,sd);
        return "ok";
    }

    @RequestMapping("/del")
    public String del(int goodsId){
        service.del(goodsId);
        return "ok";
    }
    @RequestMapping("/update")
    public String update(int goodsId,int price){
        service.update(goodsId, price);
        return "ok";
    }

    @RequestMapping("/delAllByStore")
    public String delAllByStore(int storeId) {
        service.delAllByStore(storeId);
        return "ok";
    }

    @RequestMapping("/addAllByStore")
    public String addAllByStore(int storeId) {
        service.addAllByStore(storeId);
        return "ok";
    }
}
